import { Injectable } from '@nestjs/common';
import { FriendDto } from './friend.dto';
import { PrismaService } from '../../prisma/prisma.service';
import { ResponseFactory } from '../result/result.factory';

enum FriendStatus {
  Pending = 'pending',
  Accepted = 'accepted',
  Blocked = 'blocked',
}

@Injectable()
export class FriendService {
  constructor(private prisma: PrismaService) {}

  async addFriend(userIM_ID: string, friendDto: FriendDto) {
    const { im_id: targetIM_ID, reason } = friendDto;
    if (userIM_ID === targetIM_ID)
      return ResponseFactory.info('不能添加自己为好友');
    const [user, target] = await Promise.all([
      this.prisma.user_info.findUnique({ where: { im_id: userIM_ID } }),
      this.prisma.user_info.findUnique({ where: { im_id: targetIM_ID } }),
    ]);
    if (!user || !target) return ResponseFactory.info('用户不存在');

    // 查找是否自己已经发过请求
    const outgoingRequest = await this.prisma.friend_relation.findUnique({
      where: { im_id1_im_id2: { im_id1: user.im_id, im_id2: target.im_id } },
    });

    if (outgoingRequest) {
      const statusMessage =
        {
          [FriendStatus.Pending]: '已发送申请，请等待对方同意',
          [FriendStatus.Accepted]: '你们已经是好友',
          [FriendStatus.Blocked]: '你已拉黑对方',
        }[outgoingRequest.status] || '状态异常，请联系管理员';
      return ResponseFactory.info(statusMessage);
    }

    // 查找对方是否发给你（互加情况）
    const incomingRequest = await this.prisma.friend_relation.findUnique({
      where: {
        im_id1_im_id2: { im_id1: target.im_id, im_id2: user.im_id },
      },
    });

    if (incomingRequest) {
      if (incomingRequest.status === FriendStatus.Pending) {
        // 互加，直接变成好友
        await this.prisma.friend_relation.update({
          where: {
            im_id1_im_id2: { im_id1: target.im_id, im_id2: user.im_id },
          },
          data: { status: FriendStatus.Accepted },
        });
        return ResponseFactory.info('你已通过对方的好友请求，添加成功');
      }

      if (incomingRequest.status === FriendStatus.Accepted) {
        return ResponseFactory.info('你们已经是好友');
      }

      return ResponseFactory.info('请求状态异常，请联系管理员');
    }

    // 都没有 → 创建好友请求
    await this.prisma.friend_relation.create({
      data: {
        im_id1: user.im_id,
        im_id2: target.im_id,
        reason,
        status: FriendStatus.Pending,
      },
    });
    await this.prisma.message.create({
      data: {
        group_id: null,
        content: friendDto.reason ?? '请求添加你为好友',
        message_type: 'text',
        send_time: new Date(),
        receiver_im_id: targetIM_ID,
        sender_im_id: userIM_ID,
      }
    })

    return ResponseFactory.info('好友请求已发送');
  }

  async accept({
    to_im_id,
    from_im_id,
  }: {
    to_im_id: string;
    from_im_id: string;
  }) {
    const request = await this.prisma.friend_relation.findFirst({
      where: {
        im_id1: from_im_id, // 发起请求方
        im_id2: to_im_id, // 接收方
        status: 'pending',
      },
    });

    // 2. 不存在请求，抛出异常
    if (!request) {
      return ResponseFactory.info('未找到待处理的好友请求');
    }

    // 3. 更新状态为已接受
    await this.prisma.friend_relation.update({
      where: { id: request.id },
      data: {
        status: 'accepted',
      },
    });
    return ResponseFactory.success(null, '已接受好友请求');
  }

  async block({
    to_im_id,
    from_im_id,
  }: {
    to_im_id: string;
    from_im_id: string;
  }) {
    // 1. 查找是否已存在任意方向的关系记录
    const existing = await this.prisma.friend_relation.findFirst({
      where: {
        OR: [
          { im_id1: from_im_id, im_id2: to_im_id },
          { im_id1: to_im_id, im_id2: from_im_id },
        ],
      },
    });
    if (existing) {
      // 2. 已有关系，更新为 Blocked
      if (existing.status != FriendStatus.Blocked) {
        await this.prisma.friend_relation.update({
          where: { id: existing.id },
          data: {
            status: FriendStatus.Blocked,
          },
        });
      }
    } else {
      // 3. 无记录，新增 Blocked
      await this.prisma.friend_relation.create({
        data: {
          im_id1: from_im_id,
          im_id2: to_im_id,
          status: FriendStatus.Blocked,
          create_time: new Date(),
        },
      });
    }
    return ResponseFactory.success(null, '该用户已被拉黑');
  }

  async getIncomingFriendRequests(im_id: string) {
    const requests = await this.prisma.friend_relation.findMany({
      where: {
        im_id2: im_id,
        status: FriendStatus.Pending,
      },
      include: {
        user_info_friend_relation_im_id1Touser_info: {
          select: {
            im_id: true,
            username: true,
            avatar: true,
          },
        },
      },
      orderBy: {
        create_time: 'desc',
      },
    });
    const data = requests.map((req) => ({
      from_im_id: req.im_id1,
      username: req.user_info_friend_relation_im_id1Touser_info.username,
      avatar: req.user_info_friend_relation_im_id1Touser_info.avatar,
      reason: req.reason,
      create_time: req.create_time,
    }));
    return data.length
      ? ResponseFactory.success(data, '查询成功')
      : ResponseFactory.info('暂未查询到数据');
  }

  async getOutgoingFriendRequests(im_id: string) {
    const requests = await this.prisma.friend_relation.findMany({
      where: {
        im_id1: im_id,
        status: FriendStatus.Pending,
      },
      include: {
        user_info_friend_relation_im_id2Touser_info: {
          // 这是我加的那个人的信息
          select: {
            username: true,
            avatar: true,
            im_id: true,
          },
        },
      },
      orderBy: {
        create_time: 'desc',
      },
    });

    const data = requests.map((req) => ({
      to_im_id: req.im_id2,
      username: req.user_info_friend_relation_im_id2Touser_info.username,
      avatar: req.user_info_friend_relation_im_id2Touser_info.avatar,
      reason: req.reason,
      create_time: req.create_time,
    }));
    return data.length
      ? ResponseFactory.success(data, '查询成功')
      : ResponseFactory.info('暂未查询到数据');
  }

  async searchFriend(im_id: string) {
    const data = await this.prisma.user_info.findUnique({
      where: { im_id },
    });
    return data
      ? ResponseFactory.success(data, '查询成功')
      : ResponseFactory.error('查询失败');
  }

  async searchContactList(im_id: string) {
    // 自己发起
    const list1 = await this.prisma.friend_relation.findMany({
      where: { im_id1: im_id, status: 'accepted' },
      select: {
        user_info_friend_relation_im_id2Touser_info: {
          select: {
            username: true,
            sex: true,
            avatar: true,
            im_id: true,
          }
        }
      }
    });

    // 对方发起
    const list2 = await this.prisma.friend_relation.findMany({
      where: { im_id2: im_id, status: 'accepted' },
      select: {
        user_info_friend_relation_im_id1Touser_info: {
          select: {
            username: true,
            sex: true,
            avatar: true,
            im_id: true,
          }
        }
      }
    });

    // 提取好友基本信息
    const baseFriends = [
      ...list1.map(item => item.user_info_friend_relation_im_id2Touser_info),
      ...list2.map(item => item.user_info_friend_relation_im_id1Touser_info),
    ];

    // 获取每个好友的最近一条消息（私聊）
    const enrichedFriends = await Promise.all(
      baseFriends.map(async friend => {
        const lastMessage = await this.prisma.message.findFirst({
          where: {
            group_id: null,
            OR: [
              { sender_im_id: im_id, receiver_im_id: friend.im_id },
              { sender_im_id: friend.im_id, receiver_im_id: im_id }
            ]
          },
          orderBy: { send_time: 'desc' },
          select: {
            content: true,
            send_time: true,
            sender_im_id: true,
          }
        });

        return {
          ...friend,
          lastMessage: lastMessage
            ? {
              content: lastMessage.content,
              send_time: lastMessage.send_time,
              isMe: lastMessage.sender_im_id === im_id,
            }
            : null
        };
      })
    );
    console.log(enrichedFriends);
    return ResponseFactory.success(enrichedFriends, '查询成功');
  }

  async searchChat(user_im_id: string, im_id: string) {
    const raw = await this.prisma.message.findMany({
      where: {
        group_id: null,
        OR: [
          { sender_im_id: user_im_id, receiver_im_id: im_id },
          { sender_im_id: im_id, receiver_im_id: user_im_id }
        ]
      },
      orderBy: {
        send_time: 'desc'
      },
      select: {
        sender_im_id: true,
        content: true,
        message_type: true,
        send_time: true
      }
    });
    const result = raw.map((msg) => ({
      content: msg.content,
      message_type: msg.message_type,
      send_time: msg.send_time,
      isMe: msg.sender_im_id === user_im_id
    }));
    return ResponseFactory.success(result, '查询成功');
  }
}
